package com.martinzhuang.scan_sd_card;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by martinzhuang on 9/19/15.
 */

public class ListOk extends ListActivity {

    ArrayAdapter arrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, fileToStr(MainActivity.mfileList));
        setListAdapter(arrayAdapter);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);

        if (MainActivity.mfileList.get(position).getName().endsWith(".mp4")) {
            intent.setDataAndType(Uri.fromFile(MainActivity.mfileList.get(position)), "video/mp4");
        } else if (MainActivity.mfileList.get(position).getName().endsWith(".mp3")) {
            intent.setDataAndType(Uri.fromFile(MainActivity.mfileList.get(position)), "audio/mp3");
        } else {
            intent.setDataAndType(Uri.fromFile(MainActivity.mfileList.get(position)), "image/*");
        }

        startActivity(intent);
        super.onListItemClick(l, v, position, id);
    }

    @Override
    protected void onStop() {
        super.onStop();
        MainActivity.mfileList.clear();
    }

    private String[] fileToStr(List<File> mfileList) {

        List<String> fileListStr = new ArrayList<String>();

        for (int i = 0; i < mfileList.size(); i++) {
            String fileName = mfileList.get(i).getName();
            fileListStr.add(fileName);
        }
        return fileListStr.toArray(new String[0]);
    }

}
